package com.jy.phonemng.biz.minacodec;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

public class ImageResponseDecoder extends CumulativeProtocolDecoder {

    // private static final String DECODER_STATE_KEY = ImageResponseDecoder.class.getName() + ".STATE";

    public static final int MAX_IMAGE_SIZE = 5 * 1024 * 1024;

    @Override
    protected boolean doDecode(IoSession session, IoBuffer bufferIn, ProtocolDecoderOutput out)
                                                                                               throws Exception {
        System.out.println("==ImageResponse decode start == Buffer remain:" + bufferIn.remaining());

        int pos = bufferIn.position();

        //flag
        int flagLen = bufferIn.getInt();
        System.out.println("ImageResponse decode flagLen=" + flagLen);
        byte[] flagBytes = new byte[flagLen];
        bufferIn.get(flagBytes);
        String flag = new String(flagBytes);

        //image
        int imageLen = bufferIn.getInt();
        System.out.println("ImageResponse decode imageLen=" + imageLen);
        if (bufferIn.remaining() < imageLen) {
            bufferIn.position(pos);
            return false;
        }
        byte[] imageByte = new byte[imageLen];

        System.out.println("image decode buffer left:" + bufferIn.remaining());
        bufferIn.get(imageByte);
        //
        ImageResponse response = new ImageResponse(imageByte);
        response.setFlag(flag);

        out.write(response);
        System.out.println("==ImageResponse decode end ==");
        return true;
    }

    /*private BufferedImage readImage(IoBuffer in) throws IOException {
        int length = in.getInt();
        byte[] bytes = new byte[length];
        in.get(bytes);
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        return ImageIO.read(bais);
    }*/

}
